package com.interfaces;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.common.web.CommonJspKeys;
import com.common.web.CommonKeys;
import com.common.web.Json;
import com.common.web.ReturnCodes;
import com.core.guarantee.GuaranteeJspKeys;
import com.core.guarantee.bo.GuaranteeBo;
import com.core.guarantee.dto.GuaranteeSearchCondition;
import com.core.guarantee.pojo.Guarantee;
import com.core.sendAgent.dto.SendAgentSearchCondition;
import com.core.sysConfig.bo.SysConfigBo;
import com.core.user.bo.UserBo;
import com.core.user.pojo.User;
import com.core.visitor.bo.VisitorBo;
import com.core.visitor.dto.VisitorSearchCondition;
import com.core.visitor.pojo.Visitor;
import com.util.Consts;
import com.util.DataBaseUtil;
import com.util.ExceInputUtil;
import com.util.GsonUtil;
import com.util.UploadUtil;
import com.util.exception.ComRuntimeException;
import com.util.exception.ComSystemException;
import com.util.framework.BaseController;

@Controller
public class GuaranteeController extends BaseController {
	@Resource
	private GuaranteeBo guaranteeBo;
	@Resource
	private VisitorBo visitorBo;
	@Resource
	private UserBo userBo;
	@Resource
	private UploadUtil uploadUtil;
	@Resource
	private ExceInputUtil exceInputUtil;
	@Resource
	private SysConfigBo sysConfigBo;
	protected Logger log = Logger.getLogger(this.getClass());
	public static final String URL_ENTITY = "/guarantee";
	public static final String URL_ADD_UPDATE = URL_ENTITY + "/add_update";
	public static final String URL_UPDATE = URL_ENTITY + "/update";
	public static final String URL_DEL = URL_ENTITY + "/del";
	public static final String URL_DB_SEARCH = URL_ENTITY + "/search";
	public static final String URL_GOTO_MAIN_PAGE = URL_ENTITY + "/goto_main_page";
	public static final String URL_GOTO_ADD_UPDATE_PAGE = URL_ENTITY + "/goto_add_update_page";
	public static final String URL_GOTO_ADD_PAGE = URL_ENTITY + "/goto_add_page";
	public static final String URL_GOTO_UPDATE_PAGE = URL_ENTITY + "/goto_update_page";
	public static final String URL_UPDATESTATE = URL_ENTITY + "/updateState";
	public static final String URL_DOWNLOADPDF = URL_ENTITY + "/downloadPDF";
	public static final String URL_CHECKDPDF = URL_ENTITY + "/checkPDF";
	public static final String URL_UPLOAD = URL_ENTITY + "/upload";

	@ResponseBody
	@RequestMapping(value = URL_DB_SEARCH, method = RequestMethod.POST, produces = { "application/json;charset=utf-8" })
	public Object searchData(GuaranteeSearchCondition sc, HttpSession session) {
		User userInfo = (User) session.getAttribute(CommonKeys.SESSION_USER);
		User userInfo2 = userBo.getById(userInfo);
		String msg = "";
		sc.setAddTravelId(userInfo2.getTravelAgentId());
		List<Guarantee> data = guaranteeBo.getPojoList(sc, userInfo2);
		DataBaseUtil<Guarantee> db = new DataBaseUtil<Guarantee>();
		int totalCount = guaranteeBo.getPojoListCnt(sc, userInfo2);
		if (data.size() == 0) {
			msg = "{\"draw\":" + sc.getDraw() + ",\"recordsTotal\":0,\"recordsFiltered\":0,\"data\": []}";
		} else {
			db.setTotalCount(totalCount);
			db.setRecordsFiltered(totalCount);
			db.setData(data);
			msg = GsonUtil.gson.toJson(db);
		}
		return msg;
	}

	@ResponseBody
	@RequestMapping(value = URL_ADD_UPDATE, method = RequestMethod.POST)
	public Json add(GuaranteeSearchCondition sc, HttpSession session) {
		Json json = new Json();
		Visitor visitor = new Visitor();
		User userInfo = (User) session.getAttribute(CommonKeys.SESSION_USER);
		User userInfo2 = userBo.getById(userInfo);
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd");
		try {
			sc.setAddDate(new Date());
			sc.setAddUserId(userInfo2.getId().toString());
			sc.setAddTravelId(userInfo2.getTravelAgentId());
			sc.setIsVisa(0);
			if (dateFormat.parse(sc.getIncomingDate()).getTime()>dateFormat.parse(sc.getLeaveDate()).getTime()){
                json.setReturnCode(101);
                return json;
            }
			guaranteeBo.add(sc);
			visitor.setName(sc.getFirstPersonName());
			visitor.setPinyinName(sc.getPinyinName());
			visitor.setVisaInfoId(sc.getId());
			visitor.setIsLead("1");
			visitorBo.add(visitor);
			json.setNowId(sc.getId());
			json.setSuccess(true);
			json.setReturnCode(0);
		} catch (ComRuntimeException e) {
			json = new Json(e.getErrorCode(), e.getMessage());
		} catch (ComSystemException e) {
			log.error("error", e);
			json = new Json(e.getErrorCode(), "系统忙... " + e.getMessage());
		} catch (Throwable e) {
			log.error("error", e);
			json = new Json(ReturnCodes.SYSTEM_EXCEPTION, "系统忙... " + e.getMessage());
		}
		return json;
	}

	@ResponseBody
	@RequestMapping(value = URL_UPDATE, method = RequestMethod.POST, produces = { "application/json;charset=utf-8" })
	public Json update(GuaranteeSearchCondition sc, HttpSession session) {
		Json json = new Json();
		Guarantee tempGuarantee = guaranteeBo.getById(sc);
		Visitor visitor = visitorBo.getFirstVisitor(sc.getId());
		try {

			if (tempGuarantee != null) {
				visitor.setName(sc.getFirstPersonName());
				visitor.setPinyinName(sc.getPinyinName());
				guaranteeBo.update(sc);
				visitorBo.update(visitor);
				json.setSuccess(true);
				json.setReturnCode(0);
			}
		} catch (ComRuntimeException e) {
			json = new Json(e.getErrorCode(), e.getMessage());
		} catch (ComSystemException e) {
			log.error("error", e);
			json = new Json(e.getErrorCode(), "系统忙... " + e.getMessage());
		} catch (Throwable e) {
			log.error("error", e);
			json = new Json(ReturnCodes.SYSTEM_EXCEPTION, "系统忙... " + e.getMessage());
		}
		return json;
	}

	@ResponseBody
	@RequestMapping(value = URL_DEL, method = RequestMethod.POST, produces = { "application/json;charset=utf-8" })
	public Json del(GuaranteeSearchCondition sc, HttpSession session, HttpServletRequest request) {
		String items = request.getParameter("delitems");
		String[] strs = items.split(",");
		Json json = new Json();
		Guarantee tempGuarantee = new Guarantee();
		VisitorSearchCondition vsc = new VisitorSearchCondition();
		for (int i = 0; i < strs.length; i++) {
			try {
				tempGuarantee.setId(Long.parseLong(strs[i]));
				vsc.setVisaInfoId(Long.parseLong(strs[i]));
				List<Visitor> visitorList = visitorBo.getVisitorList(vsc);
				guaranteeBo.del(tempGuarantee);
				for (Visitor visitor : visitorList) {
					visitorBo.del(visitor);
				}
				json.setSuccess(true);
			} catch (ComRuntimeException e) {
				json = new Json(e.getErrorCode(), e.getMessage());
			} catch (ComSystemException e) {
				log.error("error", e);
				json = new Json(e.getErrorCode(), "系统忙... " + e.getMessage());
			} catch (Throwable e) {
				log.error("error", e);
				json = new Json(ReturnCodes.SYSTEM_EXCEPTION, "系统忙... " + e.getMessage());
			}
		}
		return json;
	}

	@ResponseBody
	@RequestMapping(value = URL_UPDATESTATE, method = RequestMethod.POST)
	public Json updateState(HttpServletRequest request) {
		String items = request.getParameter("delitems");
		String afterState = request.getParameter("afterState");
		String[] strs = items.split(",");
		Json json = new Json();
		Guarantee tempGuarantee = new Guarantee();
		for (int i = 0; i < strs.length; i++) {
			try {
				tempGuarantee.setId(Long.parseLong(strs[i]));
				tempGuarantee.setState(afterState);
				guaranteeBo.updateState(tempGuarantee);
				json.setSuccess(true);
			} catch (ComRuntimeException e) {
				json = new Json(e.getErrorCode(), e.getMessage());
			} catch (ComSystemException e) {
				log.error("error", e);
				json = new Json(e.getErrorCode(), "系统忙... " + e.getMessage());
			} catch (Throwable e) {
				log.error("error", e);
				json = new Json(ReturnCodes.SYSTEM_EXCEPTION, "系统忙... " + e.getMessage());
			}
		}
		return json;
	}

	// 文件上传wbq
	@RequestMapping(value = URL_UPLOAD, method = RequestMethod.POST)
	@ResponseBody
	public int uploadFile(@RequestParam("file1") CommonsMultipartFile fileExcel, HttpServletRequest req, HttpServletResponse response, @RequestParam("txtId") String txtId, @RequestParam("otherNum") String otherNum)
			throws IOException {
		String road = uploadUtil.uploadFile(fileExcel, txtId);
		log.info(road);
		int resString = exceInputUtil.inputExcelReturn(road, otherNum);
		// 导入失败将导入的文件删除
		if (resString != 200) {
			File file = new File(road);
			if (file.exists() && file.isFile()) {
				if (file.delete()) {
					log.info("删除文件" + road + "成功!");
				}
			}
		} else {// 更改归国报告状态状态
			Guarantee tempGuarantee = new Guarantee();
			tempGuarantee.setId(Long.parseLong(txtId));
			tempGuarantee.setNumber(Integer.parseInt(otherNum));
			tempGuarantee.setReturnReportState(String.valueOf(Consts.RETURN_REPORT_STATE_UPLOADED));
			guaranteeBo.updateReturnState(tempGuarantee);
		}

		return resString;
	}

	// 下载pdf
	@RequestMapping(value = URL_DOWNLOADPDF, method = RequestMethod.GET)
	@ResponseBody
	public HttpServletResponse downloadPDF(@RequestParam("id") Long id, HttpServletResponse response) {
		GuaranteeSearchCondition sc = new GuaranteeSearchCondition();
		sc.setId(id);
		Guarantee guarantee = guaranteeBo.getById(sc);
		// 归报PDF状态
		Date PDFDate = guarantee.getReturnReportPdfDownloadTime();

		String PDFDateString = "";
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMM");
		PDFDateString = formatter.format(PDFDate);
		// 获取路径
		String rootFold = sysConfigBo.getByKeyNo(Consts.FOLD_ROOT).getKey_value();
		String returnReportPdfFold = sysConfigBo.getByKeyNo(Consts.FOLD_RETURN_REPORT_PDF).getKey_value();
		String upDownloadPath = rootFold + File.separator + returnReportPdfFold;// 上一层目录
		String downloadPath = upDownloadPath + File.separator + PDFDateString + File.separator + guarantee.getId() + ".pdf";
		// 开始输出
		File outfile = new File(downloadPath);
		String filename = outfile.getName();// 获取文件名称
		try {
			InputStream fis = new BufferedInputStream(new FileInputStream(downloadPath));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer); // 读取文件流
			fis.close();
			response.reset();
			response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.replaceAll(" ", "").getBytes("utf-8"), "iso8859-1")); // 返回头 文件名
			response.addHeader("Content-Length", "" + outfile.length());
			response.setContentType("application/octet-stream"); // 设置数据种类
			OutputStream os = new BufferedOutputStream(response.getOutputStream());
			os.write(buffer); // 输出文件
			os.flush();
			os.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return response;
	}

	@RequestMapping(value = URL_CHECKDPDF, method = RequestMethod.POST)
	@ResponseBody
	public int checkPDF(@RequestParam("id") Long id, HttpServletResponse response) {
		GuaranteeSearchCondition sc = new GuaranteeSearchCondition();
		sc.setId(id);
		Guarantee guarantee = guaranteeBo.getById(sc);
		// 归报PDF状态
		String state = guarantee.getReturnReportPdfDownloadState();
		if (state == null || !state.equals(String.valueOf(Consts.RETURN_REPORT_DOWNLOAD_STATE_SUCC))) {
			return Consts.ERR_STATE_NOT_OK;
		}
		Date PDFDate = guarantee.getReturnReportPdfDownloadTime();
		if (PDFDate == null) {
			return Consts.ERR_FILE_NOT_FOUND;
		}
		String PDFDateString = "";
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMM");
		PDFDateString = formatter.format(PDFDate);
		// 获取路径
		String rootFold = sysConfigBo.getByKeyNo(Consts.FOLD_ROOT).getKey_value();
		String returnReportPdfFold = sysConfigBo.getByKeyNo(Consts.FOLD_RETURN_REPORT_PDF).getKey_value();
		String upDownloadPath = rootFold + File.separator + returnReportPdfFold;// 上一层目录
		String downloadPath = upDownloadPath + File.separator + PDFDateString + File.separator + guarantee.getId() + ".pdf";
		// 开始检测
		try {
			InputStream fis = new BufferedInputStream(new FileInputStream(downloadPath));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer); // 读取文件流
			fis.close();
		} catch (FileNotFoundException e) {
			return Consts.ERR_FILE_NOT_FOUND;
		} catch (IOException e) {
			return Consts.ERR_FILE_NOT_FOUND;
		}
		return Consts.SUCCESS;
	}

	@RequestMapping(value = URL_GOTO_MAIN_PAGE, method = RequestMethod.GET)
	public ModelAndView gotoMainPage(HttpSession session, SendAgentSearchCondition sc) {
		User userInfo = (User) session.getAttribute(CommonKeys.SESSION_USER);
		ModelAndView modelAndView = new ModelAndView("/guarantee/guarantee_main");
		modelAndView.addObject(CommonJspKeys.JspParam_SessionUserInfo, userInfo);
		return modelAndView;
	}

	@RequestMapping(value = URL_GOTO_ADD_UPDATE_PAGE, method = RequestMethod.GET)
	public ModelAndView URL_GOTO_ADD_UPDATE_PAGE(HttpSession session) {
		User userInfo = (User) session.getAttribute(CommonKeys.SESSION_USER);
		ModelAndView modelAndView = new ModelAndView("guarantee/guarantee_add");
		modelAndView.addObject(CommonJspKeys.JspParam_SessionUserInfo, userInfo);
		return modelAndView;
	}

	@RequestMapping(value = URL_GOTO_UPDATE_PAGE, method = RequestMethod.GET)
	public ModelAndView URL_GOTO_UPDATE_PAGE(GuaranteeSearchCondition sc, HttpSession session) {
		User userInfo = (User) session.getAttribute(CommonKeys.SESSION_USER);
		Guarantee sc1 = guaranteeBo.getById(sc);
		Visitor visitor = visitorBo.getFirstVisitor(sc.getId());
		if (visitor!=null){
            sc1.setPinyinName(visitor.getPinyinName());
            sc1.setFirstPersonName(visitor.getName());
        }

		ModelAndView modelAndView = new ModelAndView("guarantee/guarantee_update");
		modelAndView.addObject(CommonJspKeys.JspParam_SessionUserInfo, userInfo);
		modelAndView.addObject(GuaranteeJspKeys.JspParam_Guarantee, sc1);
		return modelAndView;
	}
}
